/*
 * author      : 吴中勤 
 * date        : 2019/3/19
 * description : TODO
 */

package org.wzq.learn;

import java.util.Random;

public class TestInheritableThreadLocal {

    InheritableThreadLocal<Integer> value = new InheritableThreadLocal<>();
    ThreadLocal<Integer> value2 = new ThreadLocal<>();

    ThreadLocal<Integer> value22 = ThreadLocal.withInitial(() -> {
        int aInt = new Random().nextInt(100);
        System.out.printf("init thread=%s,value22=%d \n", Thread.currentThread().getName(), aInt);
        return aInt;
    });

    static ThreadLocal<Integer> value3 = ThreadLocal.withInitial(() -> {
        int aInt = new Random().nextInt(100);
        System.out.printf("init thread=%s,value3=%d \n", Thread.currentThread().getName(), aInt);
        return aInt;
    });

    public TestInheritableThreadLocal() {
        Random rdm = new Random();
        Integer aInt = rdm.nextInt(100);
        System.out.printf("TestInheritableThreadLocal init thread=%s, value=%d, value2=%d\n",
                Thread.currentThread().getName(),
                aInt, aInt
        );
        value.set(aInt);
        value2.set(aInt);
    }

    public static void main(String[] args) throws InterruptedException {
        TestInheritableThreadLocal testInheritableThreadLocal = new TestInheritableThreadLocal();
        new Thread(() -> {
            System.out.printf("thread=%s, value=%d, value2=%d, value22=%d, value3=%d\n",
                    Thread.currentThread().getName(),
                    testInheritableThreadLocal.value.get(),  // InheritableThreadLocal 子线程可见 且继承
                    testInheritableThreadLocal.value2.get(), // ThreadLocal 子线程不可见
                    testInheritableThreadLocal.value22.get(),// ThreadLocal 子线程不可见
                    testInheritableThreadLocal.value3.get()  // 静态变量, 子线程单独初始化
            );
        }).start();

        Thread.sleep(1000);
        System.out.printf("==========\n");
        System.out.printf("thread=%s, value=%d, value2=%d, value22=%d, value3=%d\n",
                Thread.currentThread().getName(),
                testInheritableThreadLocal.value.get(),  // InheritableThreadLocal 子线程可见 且继承
                testInheritableThreadLocal.value2.get(), // ThreadLocal 子线程不可见
                testInheritableThreadLocal.value22.get(),// ThreadLocal 子线程不可见
                testInheritableThreadLocal.value3.get()  // 静态变量, 子线程单独初始化
        );
        /*

TestInheritableThreadLocal init thread=main, value=67, value2=67

init thread=Thread-0,value22=77
init thread=Thread-0,value3=71
thread=Thread-0, value=67, value2=null, value22=77, value3=71
==========
init thread=main,value22=38
init thread=main,value3=29
thread=main, value=67, value2=67, value22=38, value3=29

         */
    }
}
